import threading
import time

import cv2
import numpy as np

# 保存图片的间隔时间
SAVE_INTERVAL = 5


class myThread(threading.Thread):
    def __init__(self, name, rtsp_path, points):
        threading.Thread.__init__(self)
        self.name = name
        self.rtsp_path = rtsp_path
        self.points = points

    def run(self):
        print("开始线程：" + self.name)
        add_new_cam(rtsp_path, points, self.name)
        print("退出线程：" + self.name)


def add_new_cam(rtsp_path, points, pool_id):
    # 创建模型
    mog = cv2.createBackgroundSubtractorMOG2()  # 定义高斯混合模型对象 mog
    gmg = cv2.bgsegm.createBackgroundSubtractorGMG()
    knn = cv2.createBackgroundSubtractorKNN(detectShadows=False)

    # 绘制蒙版

    cap = cv2.VideoCapture(rtsp_path)
    ret, frame = cap.read()
    mask = np.zeros(frame.shape, np.uint8)

    for point in points:
        point[0] = point[0] * frame.shape[1]
        point[1] = point[1] * frame.shape[0]

    points = np.array(points)
    mask = cv2.fillPoly(mask, [points], (255, 255, 255))

    # 初始化计时器用于判断时间
    time_now = time.time()

    # while 1 :
    #     a = time.time()
    #     ret, frame = cap.read()
    #     b = time.time()
    #     print(b - a)
    while 1:
        a = time.time()

        ret, frame = cap.read()
        frame_to_save = frame.copy()
        frame_to_show = frame.copy()
        frame = cv2.bitwise_and(frame, mask)
        frame = cv2.resize(frame, (320, 240))

        frame_to_show = cv2.resize(frame_to_show, (320, 240))

        # 混合高斯模型
        fgmask = mog.apply(frame)  # 使用前面定义的高斯混合模型对象 mog 当前帧的运动目标检测，返回二值图像
        gray_frame = fgmask.copy()
        kernel = np.ones((5, 5), np.uint8)
        gray_frame = cv2.morphologyEx(gray_frame, cv2.MORPH_OPEN, kernel)
        # 返回值： contours，轮廓的坐标。 hierarchy，各个框之间父子关系，不常用。
        contours, hierarchy = cv2.findContours(gray_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # 绘制每一个轮廓框到原始图像 frame 中
        for contour in contours:
            if cv2.contourArea(contour) < 1500:  # 计算候选框的面积，如果小于1500，跳过当前候选框
                continue
            (x, y, w, h) = cv2.boundingRect(contour)  # 根据轮廓，得到当前最佳矩形框
            cv2.rectangle(frame_to_show, (x, y), (x + w, y + h), (255, 255, 0), 2)  # 将该矩形框画在当前帧 frame 上

            # 根据时间间隔保存图片
            interval = time.time() - time_now

            if interval > SAVE_INTERVAL:
                # 保存图片
                s = int(round(time_now)*1000)
                cv2.imwrite(filename="image/" + str(s) + ".jpg", img=frame_to_save)
                time_now = time.time()
                print((x, y, w, h), pool_id)
                # print(time_now)
        cv2.imshow("gray", gray_frame)
        cv2.imshow("contours", frame_to_show)  # 显示当前帧
        cv2.waitKey(30)
        b = time.time()
        # print(b - a)


# rtsp = "rtsp://admin:Buchou123@192.168.1.64:554/h264/ch1/main/av_stream"
# points = np.array([(0, 0), (1000, 0), (1000, 1000), (0, 1000)])
# add_new_cam(rtsp, points)
rtsp_path = "rtsp://121.36.135.122:554/openUrl/oBidarS"
points = [[0, 0], [1, 0], [1, 1], [0, 1]]
thread = myThread(1, rtsp_path, points)
thread.start()
